// scripts/generate-components.js
const fs = require('fs')
const path = require('path')
const iconsPath = path.resolve(__dirname, '../')
const svgsPath = path.resolve(iconsPath, './svgs')
const componentsPath = path.resolve(iconsPath, './packages/components')

// 读取 svg 文件内容
function getSvg(path) {
    return fs.readFileSync(path).toString()
}

// 获取 vue 的组件名
function getVueComponentName(name) {
    return name.replace(/(^\w)|(-\w)/g, a => (a[1] || a[0]).toUpperCase())
}

// 生成 vue 组件
function generateVueContent(svgContent, fileName) {
    const vueName = fileName.split('.')[0]
    let context = `<template>\n${svgContent}\n</template>\n\n`

    context += `\
<script lang="ts" setup>
defineOptions({ name: '${getVueComponentName(vueName)}' });
</script>
`
    return context
}

// 生成 vue 文件
function createComponentFile(content, fileName, nIndex) {
    if (!fs.existsSync(componentsPath)) {
        fs.mkdirSync(componentsPath)
    }
    const vueFilePath = path.resolve(componentsPath, fileName + '.vue')

    fs.writeFile(vueFilePath, content, (err) => {
        if (err) {
            console.log(nIndex, `————————————————————————${fileName}创建失败！`);
            return
        } else {
            console.log(nIndex, `文件 ${fileName} 创建成功!`);
        }
    })
}

// 生成 vue 组件汇总文件
function createIndex(fileNames) {
    let content = `import { App } from 'vue'\n`
    const indexPath = path.resolve(componentsPath, './index.ts')
    const components = []

    fileNames.forEach(fileName => {
        const name = fileName.split('.')[0]
        const vueComponentName = getVueComponentName(name)
        components.push(vueComponentName)
        content += `import ${vueComponentName} from './${name}.vue'\n`
    })

    content += `\
    \n export {${components.join(',')}}`

    content += `\
    \n const icons = [${components.join(',')}]
    icons.forEach((icon) => {
    icon.install = function (app: App) {
        app.component(icon.name, icon)
        return app
    }
    })

    export default icons`

    fs.writeFile(indexPath, content, (err) => {
        if (err) {
            console.error(err)
            return
        }
        console.log(`文件 ${indexPath} 创建成功!`)
    })
}

// 初始化
function init() {
    // 先清除components内所有文件
    if (fs.existsSync(componentsPath)) {
        fs.rmSync(componentsPath, {
            recursive: true
        })
    }

    const svgs = fs.readdirSync(svgsPath)

    svgs.forEach((svgName, index) => {
        const svgPath = path.resolve(svgsPath, svgName)
        const ctx = getSvg(svgPath)

        const fileName = svgName.split('.')[0]

        //过滤掉<svg之前的内容
        let svgContent = ctx.substring(ctx.indexOf('<svg'));

        //在svg 后插入id
        svgContent = svgContent.replace('<svg', `<svg style="width:1em!important; height:1em!important; fill:none!important;"`);
        svgContent = svgContent.replace('<path', `<path style="fill:currentColor!important;"`);

        // 生成vue组件内容
        const vueContent = generateVueContent(svgContent, fileName)
        const nIndex = '[' + (index + 1) + '/' + svgs.length + ']';
        // 生成vue组件文件
        createComponentFile(vueContent, fileName, nIndex)
    })

    // 创建汇总index.ts
    createIndex(svgs)
}
init()
